package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.BaseException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 菜品分页查询
     * @param dishPageQuery
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQuery) {
        //1.开始分页
        PageHelper.startPage(dishPageQuery.getPage(), dishPageQuery.getPageSize());
        //2.查询菜品
        Page<DishVO> page = dishMapper.findDishByCategoryIdAndNameAndStatus(dishPageQuery);
        //3.封装数据并返回
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return pageResult;
    }

    /**
     * 修改状态
     * @param status
     * @param id
     */
    @Override
    public void updateStatusByDishId(Integer status, Long id) {
        dishMapper.updateStatusByDishid(status, id);
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     * TODO  未完成查询套餐业务 --->已完成
     */
    @Override
    @Transactional
    public void numDelete(List<Long> ids) {
       //1.查询数据库，是否存在对应的套餐中
        List<Long> setmealIdList = new ArrayList();
        ids.stream()
                .forEach(id -> {
                    Long setmealId = setmealMapper.findDishByDishId(id);
                    if(setmealId != null){
                        setmealIdList.add(setmealId);
                    }
                });

        //2.判断是否存在，，有则不能删除
        if(setmealIdList != null && setmealIdList.size() > 0){
            throw new BaseException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //3.判断状态是否为在售，是则无法删除
        List<Dish> dishList = new ArrayList<>();
        ids.stream()
                .forEach(id -> {
                    Dish dish = dishMapper.findDishStatusNumberById(id);
                    if(dish != null){
                        dishList.add(dish);
                    }
                });
        if(dishList != null && dishList.size() > 0){
            throw new BaseException(MessageConstant.SETMEAL_ON_SALE);
        }

        //4.删除菜品
        dishMapper.delete(ids);

        //5.删除菜品对应的口味
        dishFlavorMapper.deleteByDishId(ids);
    }

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void insertDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        //1.设置创建时间、用户和修改时间、用户
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setStatus(StatusConstant.DISABLE);

        //2.新增数据库菜品表数据，并返回主键id
        dishMapper.insert(dish);

        //3.新增数据库菜品口味表数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        for(DishFlavor flavor : flavors){
            flavor.setDishId(dish.getId());
        }
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //查询菜品
        Dish dish = dishMapper.findDishByDishId(id);
        //查询分类
        Category category = categoryMapper.findCategoryByCategoryId(dish.getCategoryId());
        //查询口味
        List<DishFlavor> dishFlavor = dishFlavorMapper.findDishFlavorByDishId(id);

        //封装数据
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setCategoryName(category.getName());
        dishVO.setFlavors(dishFlavor);

        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setUpdateTime(LocalDateTime.now());
        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> list(Long categoryId) {
        return dishMapper.list(categoryId);
    }

    @Override
    public List<DishVO> findByCategoryId(Long categoryId) {

        //去Redis中查找是否有该数据
        //构建key
        String key = "user:category:" + categoryId;
        String json = stringRedisTemplate.opsForValue().get(key);
        if(json != null){
            //转换成List<DishVO>
            return JSON.parseArray(json, DishVO.class);
        }

        List<DishVO> list = new ArrayList<>();
        //查询菜品
        List<Dish> dishList = dishMapper.findDishByCategoryId(categoryId);
        //查询关联的口味
        for(Dish dish : dishList){
            List<DishFlavor> dishFlavor = dishFlavorMapper.findDishFlavorByDishId(dish.getId());
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setFlavors(dishFlavor);
            list.add(dishVO);
        }

        //存入缓存中
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(list), 30, TimeUnit.MINUTES);

        return list;
    }
}
